﻿/*************************************************************************
 * Created by OhZee Creative, LLC
 * 2013
 * This code is licensed under Microsoft Public License (Ms-PL)
 * http://opensource.org/licenses/ms-pl
 * http://ozframework.codeplex.com/
 *************************************************************************/

namespace OhZeeCreative.WindowsPhone8.Helpers
{
    using Microsoft.Phone.Tasks;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading.Tasks;
    using Windows.Networking.Proximity;
    using Windows.Networking.Sockets;

    public static class BluetoothHelper
    {
        public static void OpenSettings()
        {
            ConnectionSettingsTask task = new ConnectionSettingsTask();
            task.ConnectionSettingsType = ConnectionSettingsType.Bluetooth;
            task.Show();
        }

        public static async Task<IReadOnlyList<PeerInformation>> GetPairedDevices()
        {
            PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";

            IReadOnlyList<PeerInformation> peers = null;
            try
            {
                peers = await PeerFinder.FindAllPeersAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("EXCEPTION GetPairedDevices: " + ex.Message);
            }

            return peers;
        }

        public static async Task<PeerInformation> GetPairedDevice(string deviceName)
        {
            IReadOnlyList<PeerInformation> peers = await GetPairedDevices();

            if (peers != null)
            {
                return peers.FirstOrDefault(p => p.DisplayName.Equals(deviceName));
            }

            return null;
        }

        public static async Task<StreamSocket> Connect(PeerInformation pairedDevice, string bluetoothService = "1")
        {
            if (pairedDevice == null)
            {
                throw new ArgumentNullException("pairedDevice");
            }

            StreamSocket socket = null;
            try
            {
                socket = new StreamSocket();
                // TODO: socket.Control.KeepAlive = true;
                await socket.ConnectAsync(pairedDevice.HostName, bluetoothService);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("EXCEPTION Connect", ex.Message);
                socket = null;
            }

            return socket;
        }

    }
}
